package com.audaque.springboot.foshanupload.log.aspect;

import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.URLUtil;
import cn.hutool.json.JSONUtil;
import com.audaque.springboot.foshanupload.log.model.WebLog;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.util.StopWatch;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author zgb
 * @desc ...
 * @date 2021-05-24 10:54:24
 */
@Slf4j
@Aspect
@Component
@Order(1)
public class WebLogAnnoAspect {

    @Value("${switch.webLog}")
    private boolean webLog;// 开关，true：打开，false：关闭

    @Pointcut("@annotation(com.audaque.springboot.foshanupload.log.anno.WebLogAnno)")
    public void webLog() {
    }

    @Before("webLog()")
    public void doBefore(JoinPoint joinPoint) throws Throwable {
    }

    @AfterReturning(value = "webLog()", returning = "ret")
    public void doAfterReturning(Object ret) throws Throwable {
    }

    @Around("webLog()")
    public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {

        if (!webLog) {
            return joinPoint.proceed();
        }


        Long startTime=System.currentTimeMillis();
        //记录请求信息
        WebLog webLog = new WebLog();
        webLog.setStartTime(startTime);
        //spring-framework提供了一个StopWatch类可以做类似任务执行时间控制，也就是封装了一个对开始时间，结束时间记录工具
        StopWatch sw = new StopWatch();
        // 记录开始时间
        sw.start();
        //处理业务
        Object result = joinPoint.proceed();


        Signature signature = joinPoint.getSignature();


        // 获取方法名(类全路径+.+方法名)
        String classFullName = signature.getDeclaringTypeName();
        // 比如：com.xxx.XxxService.xxxMethod
        String methodFullName = classFullName + "." + signature.getName();
        webLog.setDescription(methodFullName);


        //webLog.setUsername();
        //获取当前请求对象
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes != null) {
            HttpServletRequest request = attributes.getRequest();
            if (request != null) {
                String urlStr = request.getRequestURL().toString();
                webLog.setBasePath(StrUtil.removeSuffix(urlStr, URLUtil.url(urlStr).getPath()));
                webLog.setIp(request.getRemoteAddr());
                webLog.setMethod(request.getMethod());
                webLog.setUri(request.getRequestURI());
                webLog.setUrl(request.getRequestURL().toString());
            }
        }
        MethodSignature methodSignature = (MethodSignature) signature;
        Method method = methodSignature.getMethod();
        webLog.setParameter(getParameter(method, joinPoint.getArgs()));
        webLog.setResult(result);
        // 记录结束时间和用时
        sw.stop();
        long spendTime = sw.getTotalTimeMillis();
        webLog.setSpendTime(spendTime);


        log.debug("webLog的json:{}", JSONUtil.parse(webLog));
        return result;
    }

    /**
     * 根据方法和传入的参数获取请求参数
     */
    private Object getParameter(Method method, Object[] args) {
        List<Object> argList = new ArrayList<>();
        Parameter[] parameters = method.getParameters();
        for (int i = 0; i < parameters.length; i++) {
            //将RequestBody注解修饰的参数作为请求参数
            RequestBody requestBody = parameters[i].getAnnotation(RequestBody.class);
            if (requestBody != null) {
                argList.add(args[i]);
            }
            //将RequestParam注解修饰的参数作为请求参数
            RequestParam requestParam = parameters[i].getAnnotation(RequestParam.class);
            if (requestParam != null) {
                Map<String, Object> map = new HashMap<>();
                String key = parameters[i].getName();
                if (!StringUtils.isEmpty(requestParam.value())) {
                    key = requestParam.value();
                }
                map.put(key, args[i]);
                argList.add(map);
            }
        }
        if (argList.size() == 0) {
            return null;
        } else if (argList.size() == 1) {
            return argList.get(0);
        } else {
            return argList;
        }
    }
}
